<?php

namespace Wechat\Controller;

use Common\Lib\WxOauth;
use Think\Controller;

class CommonController extends Controller
{
    public function _initialize()
    {
        // 获取微信OpenId
        $this->session_openid();
		$this->assign('is_login', '0');
		if (D('User')->is_login()) {
         $this->assign('is_login', '1');
        }
    }
    public function ajaxReturn($code = 0, $msg = '', $data = null)
    {
        $ret = compact('code', 'msg', 'data');
        if (IS_AJAX) {
            parent::ajaxReturn($ret);
        } else {
            return $ret;
        }

    }

    /**
     * 设置微信OpenID Session
     */
    protected function session_openid()
    {
            if (!session('?ytatatmp.openid')) {
                if (C('YTATA_WEIXIN_ATTACH')) {
                    $domain = C('YTATA_WEIXIN_ATTACH_DOMAIN');
                    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];

                    if ($_GET['state']=='getwxid_susses') {
                        // 签名验证
                        $token = C('YTATA_WEIXIN_ATTACH_TOKEN');
                        $signature = md5(md5($_GET['randstr'].$token));
                        if ($_GET['signature'] != $signature) {
                            die('signature error');
                        }

                        $userinfo = json_decode($_GET['data'], true);
                        if (!empty($userinfo['openid'])) {
                            session('ytatatmp.openid', $userinfo['openid']);
                            session('ytatatmp.nickname', $userinfo['nickname']);
                            session('ytatatmp.headimgurl', $userinfo['headimgurl']);
                        } else {
                            $this->error('获取openid失败');
                        }
                    } else {
                        $redirect_uri = urlencode($redirect_uri);
                        $md5key=rand(1000,9999);

                        $url = "{$domain}?ytata_randstr={$md5key}&ytata_redirect_uri={$redirect_uri}";
//                        exit($url);
                        redirect($url);
                    }
                } else {
                    $wx_oauth = new WxOauth();
                    $openid   = $wx_oauth->getOpenid('snsapi_userinfo');
                    $userinfo = $wx_oauth->getUserInfo();
                    session('ytatatmp.openid', $userinfo['openid']);
                    session('ytatatmp.nickname', $userinfo['nickname']);
                    session('ytatatmp.headimgurl', $userinfo['headimgurl']);
                }

            }
    }
	public function check_login()
    {
		if (!D('User')->is_login()) {
			if(IS_AJAX){
			$this->ajaxReturn(0,'当前操作需要登录');
			}else{
			 $this->error("当前操作需要登录");
			}
        }
	}
	
}